<!--
 * @Author: lh
 * @Date: 2023-07-11 13:52:31
 * @LastEditors: lh
 * @LastEditTime: 2023-10-19 16:07:40
-->
<template>
  <div>
    <!-- :searchDataList="searchDataListJy" -->
    <!-- <personnel></personnel> -->
    <tabCom
      @Refresh="Refresh"
      @search-callback="searchCallback"
      :title="'程序文件审查流程'"
      :operation-api="operationApiA"
      :table-data-rule="tableDataRuleA"
      :search-data-list="searchDataListJy"
      :needPagination="true"
      :update_show_key="'id'"
      :update_show_value="[0]"
      :formDataWidth="'30%'"
      :isShowDownLoadFile="false"
      :showSearch="true"
      :isShowAddBtn="false"
      :deleteShow="false"
      :updateShow="false"
      :addButtonList="addButtonList"
      @buttonMoudle="buttonMoudle"
      ref="tabCombox"
    >
      <template #add="{ formData }">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataListJyEdit" :key="index">
          <el-input v-if="!item.type" v-model="formData[item.name]" placeholder="请输入" />
          <personnel v-model="formData[item.name]" v-else-if="item.type == 'user'"></personnel>
          <el-input
            v-else-if="item.type == 'number'"
            type="number"
            v-model="formData[item.name]"
            placeholder="请输入"
          />
          <!-- value-format="YYYY/MM/DD" -->
          <el-date-picker
            v-else-if="item.type == 'timeday'"
            v-model="formData[item.name]"
            type="date"
            format="YYYY/MM/DD"
            placeholder="请选择"
          />
          <el-date-picker
            v-else-if="item.type == 'datetime'"
            v-model="formData[item.name]"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            placeholder="请选择"
          />
          <upfilebox
            v-else-if="item.type == 'file'"
            fileType="file"
            v-model="formData[item.name]"
            v-model:name="formData[item.prop]"
          ></upfilebox>
          <el-date-picker
            @change="chooseTimeChange(formData[item.name])"
            v-else-if="item.type == 'time'"
            v-model="formData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select' && item!.list!.length > 0"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'multipleSelect'"
            multiple
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
      </template>
    </tabCom>
    <!-- 部门负责审核 -->
    <el-dialog v-model="dialogVisible" :title="'部门负责审核'" @close="resetForm" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item prop="managerType" label="是否委托">
          <el-radio-group v-model="managerType">
            <el-radio :label="1" size="large">本人操作</el-radio>
            <el-radio :label="2" size="large">委托操作</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="managerType == 1">
          <el-form-item prop="examineState" label="审核状态">
            <el-radio-group v-model="examineState">
              <el-radio :label="1" size="large">批准</el-radio>
              <el-radio :label="2" size="large">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="finalRejection" label="驳回意见" v-if="examineState == 2">
            <el-input v-model="finalRejection" placeholder="请输入" type="textarea" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="entrustUids" label="选择委托人">
            <personnel v-model="entrustUids"></personnel>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <!-- 总监审核 -->
    <el-dialog
      v-model="OpendialogVisible"
      :title="OpenType == 1 ? '总监部确认批准' : '文档人员归档'"
      @close="resetFormNew"
      width="30%"
    >
      <el-form ref="formRef" label-width="100px" label-position="left">
        <template v-if="OpenType == 1">
          <el-form-item prop="examineState" label="审核状态">
            <el-radio-group v-model="activitiesObj.examineState">
              <el-radio :label="1" size="large">批准</el-radio>
              <el-radio :label="2" size="large">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="finalRejection" label="驳回意见" v-if="activitiesObj.examineState == 2">
            <el-input v-model="activitiesObj.finalRejection" placeholder="请输入" type="textarea" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="verificationOpinions" label="验证意见">
            <el-input v-model="activitiesObj.verificationOpinions" placeholder="请输入" type="textarea" />
          </el-form-item>
          <el-form-item v-if="tablerow.isReply == '是'" prop="replyTime" label="回复时间">
            <el-date-picker
              v-model="activitiesObj.replyTime"
              type="datetime"
              format="YYYY/MM/DD HH:mm:ss"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item prop="verificationOpinions" label="回复附件文件">
            <upfilebox
              fileType="file"
              v-model="activitiesObj.fileUrl"
              v-model:name="activitiesObj.fileName"
            ></upfilebox>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="OpendialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateNew">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import tabCom from "@/components/table/indexcopy.vue"
// import { gethomeStatistics } from "@/api/home/index"
import { ref, onMounted, reactive } from "vue"
import upfilebox from "@/components/table/upfile.vue"
import personnel from "@/components/table/personnel.vue"
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage, ElMessageBox } from "element-plus"
import { managerExamine, chiefSupervisorExamine, replyNoticeContact } from "@/api/work"

const { userId } = useUserStoreHook()
const tabCombox = ref<typeof tabCom>()

onMounted(() => {
  init()
})
// 接口请求配置
const operationApiA = ref<any>([
  // { type: "add", interface: "/meetActionItemLedger/saveInfo" },
  // { type: "update", interface: "/meetActionItemLedger/updateInfo" },
  { type: "search", interface: "/noticeContactFormInput/selectMyExamineAll" }
  // { type: "delete", interface: "/meetActionItemLedger/deleteByIds" },
  // { type: "svg", interface: "/meetActionItemLedger/export" }
])
//#region  添加按钮所有逻辑
// 添加按钮
const addButtonList = [
  { name: "部门审批", type: "infill" },
  { name: "总监部审批", type: "validation" },
  { name: "文档人员归档", type: "CloseTask" }
]
const tablerow = ref() // 当前操作表单数据
// 按钮回调
const buttonMoudle = (type: string, row: any, Face: string) => {
  tablerow.value = row
  // console.log(type, row, "-*-buttonMoudle")
  switch (type) {
    case "infill": // 部门审批
      infillFn()
      break
    case "validation": // 总监部审批
      validationFn()
      break
    case "CloseTask": // 文档人员审批
      CloseTaskFn()
      break
  }
}
let dialogVisible = ref(false) // 部门负责弹框
let actionItemEvolve = ref("") // 审核状态

let managerType = ref(1) // 选择 是否委托
let examineState = ref(1) // 审核状态
let finalRejection = ref("") // 驳回意见
let entrustUids = ref("") // 委托人

// 用户审查程序文件弹框 方法
const infillFn = () => {
  // console.log("infillFn", userId)
  if (tablerow.value.examineState == 1) {
    let tabdepartmentHeadsUids = tablerow.value?.departmentHeadsUids.split(",") || []
    if (tabdepartmentHeadsUids.includes(userId.toString())) {
      dialogVisible.value = true
    } else {
      ElMessage.error("你不是该部门处理人~")
    }
  } else {
    ElMessage.error("已操作~")
  }
}
// 重置数据
const resetForm = () => {
  actionItemEvolve.value = ""
  managerType.value = 1
  examineState.value = 1
  finalRejection.value = ""
  entrustUids.value = ""
}
// 确认反馈
const handleCreate = () => {
  let params = {}

  if (managerType.value == 1) {
    // 自己操作
    if (examineState.value == 2 && !finalRejection.value) {
      ElMessage.error("请输入驳回意见~")
      return
    }
    params["examineState"] = examineState.value
    params["finalRejection"] = examineState.value == 1 ? "" : finalRejection.value
  } else {
    // 选择委托人
    if (!entrustUids.value) {
      ElMessage.error("请选择委托人~")
      return
    }
    params["entrustUids"] = entrustUids.value
  }
  params["id"] = tablerow.value.id
  params["managerType"] = managerType.value
  managerExamine(params).then((res) => {
    console.log(res, "---res")
    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      tabCombox.value.resetSearch()
      dialogVisible.value = false
      resetForm()
    }
  })
}

const OpendialogVisible = ref(false) // 开启生效发布

const OpenType = ref(1) // 1 为总监部 2 为 文档人员

// 对接数据
const activitiesObj = reactive({
  examineState: 1,
  finalRejection: "", // 驳回意见
  verificationOpinions: "", // 回复意见
  replyTime: "", // 回复时间
  fileName: "", // 附件名字
  fileUrl: "" // 附件地址
})

// 总监部审批
const validationFn = () => {
  // 当前还没验证
  if (tablerow.value.examineState == 2) {
    let tabchiefSupervisionEngineerUids = tablerow.value?.chiefSupervisionEngineerUids.split(",") || []
    if (tabchiefSupervisionEngineerUids.includes(userId.toString())) {
      OpendialogVisible.value = true
      OpenType.value = 1
    } else {
      ElMessage.error("你不是该总监部处理人~")
    }
  } else {
    if (tablerow.value.examineState < 2) {
      ElMessage({
        message: "还没到该步骤~",
        type: "warning"
      })
    } else {
      ElMessage({
        message: "已操作~",
        type: "warning"
      })
    }
  }
}
// 开启生效发布 弹框重置数据
const resetFormNew = () => {
  activitiesObj.examineState = 1
  // activitiesObj.finalRejection = ""
  for (let key in activitiesObj) {
    if (key == "examineState") {
      continue
    }
    activitiesObj[key] = ""
  }
}
// 总监部确认批准 和 文档人员审核
const handleCreateNew = () => {
  if (activitiesObj.examineState == 2 && !activitiesObj.examineState) {
    ElMessage.error("请输入驳回意见~")
    return
  }
  if (activitiesObj.examineState == 1) {
    activitiesObj.finalRejection = ""
  }
  let ajaxFn: any
  if (OpenType.value == 1) {
    // 总监部
    ajaxFn = chiefSupervisorExamine
  } else {
    // 文档
    if (!activitiesObj.verificationOpinions) {
      ElMessage.error("请输入验证意见~")
      return
    }
    if (tablerow.value.isReply == "是" && !activitiesObj.replyTime) {
      ElMessage.error("请输入回复时间~")
      return
    }
    // if (!activitiesObj.fileUrl) {
    //   ElMessage.error("请输入验证意见~")
    //   return
    // }
    ajaxFn = replyNoticeContact
  }
  ajaxFn({
    ...activitiesObj,
    id: tablerow.value.id
  }).then((res) => {
    if (res.code == 200) {
      ElMessage({ message: "发布成功", type: "success" })
      tabCombox.value.resetSearch()
      OpendialogVisible.value = false
      resetFormNew()
    }
  })
}

// 文档人员审批
const CloseTaskFn = () => {
  if (tablerow.value.examineState == 3) {
    let tabdocumentAdministratorUids = tablerow.value?.documentAdministratorUids.split(",") || []
    if (tabdocumentAdministratorUids.includes(userId.toString())) {
      OpendialogVisible.value = true
      OpenType.value = 2
    } else {
      ElMessage.error("你不是该文档处理人~")
    }
  } else {
    if (tablerow.value.examineState < 3) {
      ElMessage({
        message: "还没到该步骤~",
        type: "warning"
      })
    } else {
      ElMessage({
        message: "已操作~",
        type: "warning"
      })
    }
  }
}

//#endregion

// 搜索配置
const searchDataListJy = [
  // { name: "countersignDepartment", title: "会签部门" },
  { name: "startTime", title: "开始时间", type: "datetime" },
  { name: "endTime", title: "结束时间", type: "datetime" }
]
// 添加配置
const searchDataListJyEdit = []
// 表单配置
const tableDataRuleA = ref([
  { prop: "id", label: "id" },
  {
    prop: "inputType",
    label: "创建类型",
    type: "select",
    list: [
      { value: 1, label: "通知单", name: "通知单", id: 1 },
      { value: 2, label: "联系单", name: "联系单", id: 2 }
    ]
  },
  { prop: "projectName", label: "项目名称" },
  { prop: "communicationChannelNum", label: "通信渠道号" },
  { prop: "fileNum", label: "文件编号" },
  { prop: "engineeringName", label: "工程名称" },
  {
    prop: "engineeringType",
    label: "类型",
    type: "select",
    list: [
      { value: 1, label: "进度", name: "进度", id: 1 },
      { value: 2, label: "费用", name: "费用", id: 2 },
      { value: 3, label: "质量", name: "质量", id: 3 },
      { value: 4, label: "安全", name: "安全", id: 4 }
    ]
  },
  { prop: "mainDelivery", label: "主送" },
  { prop: "fileTheme", label: "文件主题" },
  {
    prop: "isReply",
    label: "是否回复",
    type: "select",
    list: [
      { value: "否", label: "否", name: "否", id: 0 },
      { value: "是", label: "是", name: "是", id: 1 }
    ]
  },
  { prop: "replyTimeLimit", label: "回复时限", type: "time" },
  { prop: "replyTime", label: "回复时间", type: "time" },
  { prop: "verificationOpinions", label: "验证意见" },
  {
    prop: "examineState",
    label: "审核状态",
    type: "select",
    list: [
      { value: 0, label: "待启动", name: "待启动", id: 0 },
      { value: 1, label: "待部门审核", name: "待部门审核", id: 1 },
      { value: 2, label: "待总监批准", name: "待总监批准", id: 2 },
      { value: 3, label: "待回复文件", name: "待回复文件", id: 3 },
      { value: 4, label: "驳回", name: "驳回", id: 4 },
      { value: 5, label: "结束", name: "结束", id: 5 }
    ]
  },
  {
    prop: "closeState",
    label: "关闭状态"
  },
  { prop: "remarks", label: "备注" }
])
// 初始化
const init = () => {}
// 表单刷新
const Refresh = () => {
  //用户数据概览
}
// 搜索回调
const searchCallback = (search: any) => {}
const loading = ref<boolean>(false)
const gailan = ref<any>({})
const gethomeStatisticsStar = (obj: any = {}) => {
  // loading.value = true
  // gethomeStatistics(obj).then((res: any) => {
  //   gailan.value = res.data
  //   loading.value = false
  // })
}

// 时间选择限定范围
const chooseTimeChange = (time: any) => {
  const starTime = JSON.parse(JSON.stringify(time[0]))
  const endTime = JSON.parse(JSON.stringify(time[1]))
  const minTime = new Date(insertStr(insertStr(starTime, 4, "-"), 7, "-")).getTime()
  const maxTime = new Date(insertStr(insertStr(endTime, 4, "-"), 7, "-")).getTime()
  const allow = 2592000000 //30天
  if (maxTime - minTime > allow) {
    ElMessage.warning("选择范围请在30天以内!")
    chaxunState.value = false
  } else {
    chaxunState.value = true
  }
}
</script>
<style scoped lang="scss">
.search-wrapper {
  margin: 0 auto;
  width: 98.5%;
  margin-top: 10px;
}
</style>
